package com.qwq.infrastructure.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/*
 * 接口统一返回值处理
 * */
@RestControllerAdvice(basePackages = "com.qwq.controller")
public class ApiResultWrapperHandler implements ResponseBodyAdvice<Object> {
    private final ObjectMapper _objectMapper;

    @Autowired
    public ApiResultWrapperHandler(ObjectMapper objectMapper) {
        _objectMapper = objectMapper;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ApiResult) {
            return body;
        }
        // 接口返回string会出异常，手动处理
        if (body instanceof String) {
            return _objectMapper.writeValueAsString(ApiResult.success(body));
        }
        // 返回文件之类的
        if (body instanceof byte[]) {
            return body;
        }
        return ApiResult.success(body);
    }
}
